// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// p [author] rhyme_lph
// Q [email]  rhymelph@gmail.com
// t [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/quotation_entity.dart';
import 'package:finance_app/src/utils/date_time_utils.dart';
import 'package:finance_app/src/utils/form_utils.dart';
import 'package:finance_app/src/utils/permission_utils.dart';
import 'package:finance_app/src/utils/transaction_type_utils.dart';
import 'package:finance_app/src/widgets/button/add_button.dart';
import 'package:finance_app/src/widgets/list_item/list_header_item.dart';
import 'package:finance_app/src/widgets/common_app_bar.dart';
import 'package:finance_app/src/widgets/input/search_input_field.dart';
import 'package:finance_app/src/widgets/select/quotation_number_radio.dart';
import 'package:finance_app/src/widgets/wrapper/normal_form_wrapper.dart';
import 'package:flutter/material.dart';
import 'package:finance_app/src/provider/dashboard/quotation/quotation_number_provider.dart';
import 'package:finance_app/src/router_gen/router_meta.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tuple/tuple.dart';
export 'package:finance_app/src/entities/quotation_entity.dart';

@RouterMeta(paramName: "quotationNumberPage")
class QuotationNumberPage extends StatefulWidget {
  final QuotationEntity select;
  final int contactId;

  const QuotationNumberPage({Key key, this.select, this.contactId})
      : super(key: key);

  @override
  _QuotationNumberPageState createState() => _QuotationNumberPageState();
}

class _QuotationNumberPageState extends State<QuotationNumberPage>
    with PagePresenter<QuotationNumberPage, QuotationNumberProvider> {
  @override
  void initState() {
    provider.currentSelect = widget.select;
    provider.contactId = widget.contactId;
    super.initState();
  }

  @override
  Widget get buildEmptyWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildTopWidget(),
            Expanded(
              child: super.buildEmptyWidget,
            ),
          ],
        ),
      );

  @override
  PreferredSizeWidget get appBar => getDefaultAppBar(
        title: S.current.quotation_number,
      );

  @override
  Widget get buildWidget => ColoredBox(
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildTopWidget(),
            Expanded(
              child: listBuilder<List<QuotationEntity>>(
                selector: (_, __) => __.data,
                builder: (BuildContext context, List<QuotationEntity> value,
                        Widget child) =>
                    value.isEmpty
                        ? super.buildEmptyWidget
                        : SmartRefresher(
                            controller: provider.refreshController,
                            onRefresh: provider.onRefresh,
                            onLoading: provider.onLoadMore,
                            enablePullUp: provider.hasUp,
                            child: ListView(
                              children: buildChildList(),
                            ),
                          ),
              ),
            ),
          ],
        ),
      );

  Widget _buildTopWidget() => Column(
        children: [
          SizedBox(
            height: getDp(20),
          ),
          SearchInputField(
            controller: provider.searchController,
            focusNode: provider.searchFocusNode,
          ),
          Config.hasPermission(PermissionUtils.quotation)
              ? Column(
                  children: [
                    NormalFormWrapper(
                      child: AddButton(
                        title: S.current.add_quotation,
                        onTap: provider.onNavAddQuotation,
                      ),
                    ),
                    AppSpaces.grayH05,
                  ],
                )
              : AppSpaces.h20,
        ],
      );

  List<Widget> buildChildList() {
    return provider.data.toList().map((e) => buildSliverItem(e)).toList();
  }

  Widget buildSliverItem(QuotationEntity data) {
    return listBuilder<Tuple2<QuotationEntity, bool>>(
      selector: (_, __) => Tuple2(data, data.id == __.currentSelect?.id),
      builder: (BuildContext context, Tuple2<QuotationEntity, bool> value,
              Widget child) =>
          PressedOpacityButton(
        onPressed: () => provider.onSelect(value.item1),
        child: QuotationNumberRadio(
          title: value.item1?.contact?.name ?? '',
          poNumber: value.item1.number,
          due: DateTimeUtils.formatDateTimeString(value.item1.dueAt),
          amount: value.item1.total.toDouble(),
          status: FormUtils.getStatus(
              TransactionTypeUtils.getTransactionTypeStatus(
                  value.item1.dataType),
              value.item1.status,
              0),
          unit: value.item1.currencyCode,
          isSelect: value.item2,
        ),
      ),
    );
  }

  Widget buildSliverHeader({String title}) {
    final String _title = title.isEmpty ? "*" : title;
    return ListHeaderItem(
      title: _title,
    );
  }
}
